package com.katze.boot.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.katze.boot.file.dao.FileDatabaseMapper;
import com.katze.boot.file.entity.FileDatabaseEntity;
import com.katze.boot.file.entity.FileSystemConstant.Repository;
import com.katze.boot.file.service.FileDatabaseService;
import com.katze.common.Pagination;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


/**
* 说  明： 文件库服务类，主要维护文件存储
* 作  者：admin
* 日  期：2023-12-07
*/
@Service
public class FileDatabaseServiceImpl extends ServiceImpl<FileDatabaseMapper, FileDatabaseEntity> implements FileDatabaseService {
    private static final Logger log = LoggerFactory.getLogger(FileDatabaseServiceImpl.class);

    @Override
    public Object findFileDatabases(Pagination pagination, FileDatabaseEntity fileDatabase) {
        try {
            QueryWrapper<FileDatabaseEntity> wrapper = Wrappers.query(FileDatabaseEntity.class)
                    .like(StringUtils.isNotBlank(fileDatabase.getName()), "d.name", fileDatabase.getName());
            if (pagination.isEnabled()) {
                return this.baseMapper.selectPage(pagination.toPage(), wrapper);
            } else {
                return this.baseMapper.selectList(wrapper);
            }
        } catch (Exception e) {
            log.error("获取文件库记录失败", e);
            return null;
        }
    }

    @Override
    public FileDatabaseEntity getCurrentFileDatabase() {
        FileDatabaseEntity fileDatabase  = baseMapper.selectByRepositoryId(Repository.DEFAULT_REPOSITORY_ID);
        if (fileDatabase == null) {
            throw new IllegalStateException("文件仓尚未配置文件库");
        }
        return fileDatabase;
    }

    @Override
    public boolean updateCurrentFolderId(FileDatabaseEntity fileDatabase) {
        LambdaUpdateWrapper<FileDatabaseEntity> wrapper = Wrappers.lambdaUpdate(FileDatabaseEntity.class)
                .set(StringUtils.isNotBlank(fileDatabase.getCurrentFolderId()), FileDatabaseEntity::getCurrentFolderId, fileDatabase.getCurrentFolderId())
                .eq(FileDatabaseEntity::getId, fileDatabase.getId());
        return this.update(wrapper);
    }
}
